package com.gxar.quick.ar.server.base.reference;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author CJQ
 * @version 1.0
 * @created 2023/11/20 10:38
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QimenReference {

    private final RedisTemplate redisTemplate;

    /**
     * 构建范化调用服务
     *
     * @return 范化调用服务
     */
    private GenericService buildGenericService() {
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        // 弱类型接口名
        reference.setApplication(new ApplicationConfig("qimen-provider"));
        //接口类全限定类名
        reference.setInterface("com.gxar.api.QimenService");
        reference.setCheck(false);
        //接口版本号
        reference.setVersion("1.0.0");
        reference.setTimeout(35000);
        // 声明为泛化接口
        reference.setGeneric(true);
        reference.setSerialization("fastjson");
        // 用org.apache.dubbo.rpc.service.GenericService可以替代所有接口引用
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        return cache.get(reference);
    }


    /**
     * 根据token获取用户信息
     *
     * @return
     */
    public JSONObject getMicroUser(String accessToken) {
        try {
            log.info("accessToken" + accessToken);

            Object cacheUser = redisTemplate.opsForValue().get("microUser:" + accessToken);
            String microStr = "";
            if (Objects.isNull(cacheUser)) {
                // 构建范化调用服务
                GenericService genericService = this.buildGenericService();
                //封装参数(params为Map<String, Object>，参数名和值)
                Map<String, String> params = new HashMap<>();
                params.put("accessToken", accessToken);
                String[] paramTypes = new String[params.size()];
                Object[] paramValues = new Object[params.size()];
                int i = 0;
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    paramTypes[i] = entry.getValue().getClass().getTypeName();
                    paramValues[i] = entry.getValue();
                    i++;
                }
                Object userServiceObject = genericService.$invoke("getMicroUser", paramTypes, paramValues);
                if (Objects.nonNull(userServiceObject)) {
                    microStr = JSON.toJSONString(userServiceObject);
                    log.info(microStr);
                    redisTemplate.opsForValue().set("microUser:" + accessToken, microStr, 10, TimeUnit.MINUTES);
                }
            } else {
                microStr = Objects.toString(cacheUser);
            }

            return JSON.parseObject(microStr);
        } catch (Exception e) {
            log.error("dubbo Request:" + e.getMessage());
        }

        return null;
    }

    public JSONObject microUserLottery(Long usrid, Integer activityId, Integer scanId) {
        try {
            log.info("microUserLottery userId:" + usrid + ";activityId:" + activityId + ";scanId:" + scanId);
            // 构建范化调用服务
            GenericService genericService = this.buildGenericService();
            //封装参数(params为Map<String, Object>，参数名和值)
            Map<String, String> params = new HashMap<>();
            Map<String, String> paramJson = new HashMap<>();
            paramJson.put("usrid", String.valueOf(usrid));
            paramJson.put("activityId", String.valueOf(activityId));
            paramJson.put("scanId", String.valueOf(scanId));
            params.put("param", JSON.toJSONString(paramJson));

            String[] paramTypes = new String[params.size()];
            Object[] paramValues = new Object[params.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                paramTypes[i] = entry.getValue().getClass().getTypeName();
                paramValues[i] = entry.getValue();
                i++;
            }
            Object userServiceObject = genericService.$invoke("microUserLottery", paramTypes, paramValues);
            if (Objects.nonNull(userServiceObject)) {
                log.info(JSON.toJSONString(userServiceObject));
                return JSON.parseObject(JSON.toJSONString(userServiceObject));
            }
        } catch (Exception e) {
            log.error("dubbo Request:" + e.getMessage());
        }

        return null;
    }

    public JSONObject microUserSyncLottery(Long usrid, Integer activityId, Integer scanId, String prizeHisId) {
        try {
            log.info("microUserLottery userId:" + usrid + ";activityId:" + activityId + ";scanId:" + scanId + ";prizeHisId:" + prizeHisId);
            // 构建范化调用服务
            GenericService genericService = this.buildGenericService();
            //封装参数(params为Map<String, Object>，参数名和值)
            Map<String, String> params = new HashMap<>();
            Map<String, String> paramJson = new HashMap<>();
            paramJson.put("usrid", String.valueOf(usrid));
            paramJson.put("prizeHisId", prizeHisId);
            paramJson.put("activityId", String.valueOf(activityId));
            paramJson.put("scanId", String.valueOf(scanId));
            paramJson.put("checkPrize", "0");
            params.put("param", JSON.toJSONString(paramJson));

            String[] paramTypes = new String[params.size()];
            Object[] paramValues = new Object[params.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                paramTypes[i] = entry.getValue().getClass().getTypeName();
                paramValues[i] = entry.getValue();
                i++;
            }
            Object userServiceObject = genericService.$invoke("microUserSyncLottery", paramTypes, paramValues);
            if (Objects.nonNull(userServiceObject)) {
                log.info(JSON.toJSONString(userServiceObject));
                return JSON.parseObject(JSON.toJSONString(userServiceObject));
            }
        } catch (Exception e) {
            log.error("dubbo Request:" + e.getMessage());
        }

        return null;
    }

    public JSONObject[] getUserLottery(Long usrid, Integer activityId, Integer scanId) {
        try {
            log.info("getUserLottery userId:" + usrid + ";activityId:" + activityId + ";scanId:" + scanId);
            // 构建范化调用服务
            GenericService genericService = this.buildGenericService();
            //封装参数(params为Map<String, Object>，参数名和值)
            Map<String, String> params = new HashMap<>();
            Map<String, String> paramJson = new HashMap<>();
            paramJson.put("usrid", String.valueOf(usrid));
            paramJson.put("activityId", String.valueOf(activityId));
            paramJson.put("scanId", String.valueOf(scanId));
            params.put("param", JSON.toJSONString(paramJson));

            String[] paramTypes = new String[params.size()];
            Object[] paramValues = new Object[params.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                paramTypes[i] = entry.getValue().getClass().getTypeName();
                paramValues[i] = entry.getValue();
                i++;
            }
            Object userLotteryObject = genericService.$invoke("getUserLottery", paramTypes, paramValues);
            if (Objects.nonNull(userLotteryObject)) {
                String resStr = JSON.toJSONString(userLotteryObject);
                log.info(resStr);
                return JSONObject.parseObject(resStr, JSONObject[].class);
            }
        } catch (Exception e) {
            log.error("dubbo Request:" + e.getMessage());
        }

        return null;
    }
}
